#include <iostream>
#include <string>
#include <Socket.h>
#include <Messager.h>
#include <vector>
#include <Instruction.h>

using namespace std;
int main()
{
	
	Socket socket;
	Messager messager(socket);
	string pwd = "";
	
	//如果连接出错
	if(!socket.Connect("127.0.0.1", 8888))
	{
		cout << "连接服务出错" << endl;
		exit(0);	
	}
	
	//循环输入指令
	while(true)
	{
		cout << "[" << pwd << "]";
		
		//输入指令
		string ins;
		getline(cin, ins);
		
		//指令预判断
		if(ins.size() < 2)
		{
			continue;
		}else if(ins == "exit")
		{
			break;
		}
		
		//先判断是不是cat指令，先处理之
		vector<string> args = Instruction::split(ins, " ");
		if(args.at(0) == "cat")
		{
			//如果是读取模式
			if(args.size() >= 2 && args.at(1) == "-r")
			{
				stringstream ss;
				while(true)
				{
					string line;
					getline(cin, line);
					if(line == "exit")
					{
						break;
					}
					ss << line << endl;
				}
				
				//重新构造指令
				ins += " ";
				ins += ss.str();
			}
		}
			
		//将指令发送给服务端
		if(messager.send(ins))
		{
			//接收服务端的结果
			try
			{
				pwd = messager.recv();
			}catch(string s)
			{
				goto Error;
			}
			
			cout << messager.recv();
			
		}else
		{
			goto Error;
		}
	}
	
	
	return 0;
	
	
	Error:
	{
		cout << "异常退出" << endl;
		exit(0);
	}
}